package com.wffz.controller;

import com.wffz.comm.utils.SignAPI;
import com.wffz.comm.utils.SignUtil;
import com.wffz.mapper.MoneyLogMapper;
import com.wffz.po.ClientUser;
import com.wffz.po.IncomeLog;
import com.wffz.po.MoneyLog;
import com.wffz.po.RechargeOrder;
import com.wffz.service.*;
import com.wffz.vo.SpayRechargeCallBackVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author sunlei
 * @className MoneyBackController
 * @Description
 * @date 2023-04-23 15:18
 **/
@RestController
@Slf4j
@RequestMapping("/moneyBack")
public class MoneyBackController {

    @Resource
    private UserService userService;

    @Resource
    private MoneyLogService moneyLogService;

    @Resource
    private RechargeOrderService rechargeOrderService;


    @Resource
    private MoneyLogMapper logMapper;

    @Resource
    private IncomeLogService incomeLogService;


    /**
     * @Description: [spay支付回调]
     * @Title: rechargeCallBack
     * @Author: SUNLEI
     * @Date: 2023-04-23
     * @Param: request
     * @Return: com.wffz.comm.api.ResponseResult
     * @Throws:
     */
    @RequestMapping("/spayRechargeCallBack")
    public void spayRechargeCallBack(HttpServletRequest request, HttpServletResponse response, SpayRechargeCallBackVO vo) {
        // 更改订单状态
        RechargeOrder rechargeOrder = rechargeOrderService.queryRechargeOrderByOrderId(Long.parseLong(vo.getOrderId()));
        ClientUser clientUser = userService.findUserByUserId(rechargeOrder.getUserId());
        log.info("---------------------------------------------------------------------------------------------------------------------------------------------");
        // 更改订单状态
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (vo.getStatus().equals("1")) {
            float balance = clientUser.getBalance();
            float newBalance = clientUser.getBalance() + vo.getOrderAmount();
            //            // 判断是否是第一次充值，如果是第一次  加10元
            int count = moneyLogService.moneyCount(clientUser);
            if (count <= 0) {
                newBalance += 10;
                IncomeLog incomeLog = new IncomeLog();
                incomeLog.setAmount(10f);
                incomeLog.setIncomeType("5");
                incomeLog.setUserId(clientUser.getId());
                incomeLogService.saveInComeLog(incomeLog);
            } else if (count == 1) {
                newBalance += 10;
                IncomeLog incomeLog = new IncomeLog();
                incomeLog.setAmount(10f);
                incomeLog.setIncomeType("6");
                incomeLog.setUserId(clientUser.getId());
                incomeLogService.saveInComeLog(incomeLog);
            }

            // 日志
            // 新增充值记录
            MoneyLog moneyLog = new MoneyLog();
            moneyLog.setLoginName(clientUser.getLoginName());
            moneyLog.setUserId(clientUser.getId());
            moneyLog.setMoney(vo.getOrderAmount());
            moneyLog.setBalanceBefore(balance);
            moneyLog.setBalance(newBalance);
            moneyLog.setCreateTime(new Date());
            logMapper.insert(moneyLog);
            //
            IncomeLog in = new IncomeLog();
            in.setAmount(balance);
            in.setIncomeType("8");
            in.setUserId(clientUser.getId());
            incomeLogService.saveInComeLog(in);
            // 获取总计充值数额 设置VIP级别
            Float moneyAll = moneyLogService.sumMoney(clientUser);
            if (moneyAll >= 200 && moneyAll <= 400) {
                clientUser.setVipLevel(1);
            } else if (moneyAll > 400 && moneyAll <= 1000) {
                clientUser.setVipLevel(2);
            } else if (moneyAll > 1000 && moneyAll <= 2000) {
                clientUser.setVipLevel(3);
            } else if (moneyAll > 2000 && moneyAll <= 10000) {
                clientUser.setVipLevel(4);
            } else if (moneyAll > 10000 && moneyAll <= 20000) {
                clientUser.setVipLevel(5);
            } else if (moneyAll > 20000 && moneyAll <= 50000) {
                clientUser.setVipLevel(6);
            } else if (moneyAll > 50000 && moneyAll <= 100000) {
                clientUser.setVipLevel(7);
            } else if (moneyAll > 100000) {
                clientUser.setVipLevel(8);
            }
            clientUser.setBalance(newBalance);
            clientUser.setAwayBalance(clientUser.getAwayBalance() + rechargeOrder.getExtra());
            userService.updateClientUser(clientUser);
            if (clientUser.getAwayBalance() != null && clientUser.getAwayBalance() > 0) {
                IncomeLog incomeLog = new IncomeLog();
                incomeLog.setAmount(10f);
                incomeLog.setIncomeType("8");
                incomeLog.setUserId(clientUser.getId());
                incomeLogService.saveInComeLog(incomeLog);
            }
            rechargeOrder.setOrderStatus("1");
            rechargeOrderService.updateRechargeOrder(rechargeOrder);
            pw.print("success");
            System.out.println("验签结果result的值：" + vo.getStatus() + " -->success");
        } else {
            rechargeOrder.setOrderStatus("2");
            rechargeOrderService.updateRechargeOrder(rechargeOrder);
            pw.print("Signature Error");
            System.out.println("验签结果result的值：" + vo.getStatus() + " -->Signature Error");
        }
    }

    /**
     * @Description: [支付回调]
     * @Title: rechargeCallBack
     * @Author: SUNLEI
     * @Date: 2023-04-23
     * @Param: request
     * @Return: com.wffz.comm.api.ResponseResult
     * @Throws:
     */
    @RequestMapping("/rechargeCallBack")
    public void rechargeCallBack(HttpServletRequest request, HttpServletResponse response) {
        Principal principal = request.getUserPrincipal();
        ClientUser clientUser = userService.findUserByUserName(principal.getName());
        String tradeResult = (String) request.getParameter("tradeResult");
        String mchId = (String) request.getParameter("mchId");
        String merchant_key = "";//支付秘钥，商户后台可以查看
        String mchOrderNo = (String) request.getParameter("mchOrderNo");
        String oriAmount = (String) request.getParameter("oriAmount");
        String amount = (String) request.getParameter("amount");
        String orderDate = (String) request.getParameter("orderDate");
        String orderNo = (String) request.getParameter("orderNo");
        String sign = (String) request.getParameter("sign");
        String signType = (String) request.getParameter("signType");
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("tradeResult", tradeResult);
        params.put("mchId", mchId);
        params.put("mchOrderNo", mchOrderNo);
        params.put("oriAmount", oriAmount);
        params.put("amount", amount);
        params.put("orderDate", orderDate);
        params.put("orderNo", orderNo);
        params.put("amount", amount);
        String signStr = SignUtil.sortData(params);
        log.info("tradeResult:" + tradeResult);
        log.info("实际支付金额:" + amount);
        String signInfo = signStr.toString();
        log.info("签名参数排序：" + signInfo.length() + " -->" + signInfo);
        log.info("签名：" + sign.length() + " -->" + sign);
        boolean result = false;
        if ("MD5".equals(signType)) {
            result = SignAPI.validateSignByKey(signInfo, merchant_key, sign);
        }
        log.info("验签结果result的值：" + result + " -->success");
        log.info("---------------------------------------------------------------------------------------------------------------------------------------------");
        // 更改订单状态
        RechargeOrder rechargeOrder = rechargeOrderService.queryRechargeOrderByOrderId(Long.parseLong(mchOrderNo));
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (result) {
            if (tradeResult.equals("1")) {
                float balance = clientUser.getBalance();
                float newBalance = clientUser.getBalance() + Float.parseFloat(amount);
                //            // 判断是否是第一次充值，如果是第一次  加10元
                int count = moneyLogService.moneyCount(clientUser);
                if (count <= 0) {
                    newBalance += 10;
                    IncomeLog incomeLog = new IncomeLog();
                    incomeLog.setAmount(10f);
                    incomeLog.setIncomeType("5");
                    incomeLog.setUserId(clientUser.getId());
                    incomeLogService.saveInComeLog(incomeLog);
                } else if (count == 1) {
                    newBalance += 10;
                    IncomeLog incomeLog = new IncomeLog();
                    incomeLog.setAmount(10f);
                    incomeLog.setIncomeType("6");
                    incomeLog.setUserId(clientUser.getId());
                    incomeLogService.saveInComeLog(incomeLog);
                }

                // 日志
                // 新增充值记录
                MoneyLog moneyLog = new MoneyLog();
                moneyLog.setLoginName(clientUser.getLoginName());
                moneyLog.setUserId(clientUser.getId());
                moneyLog.setMoney(Float.parseFloat(amount));
                moneyLog.setBalanceBefore(balance);
                moneyLog.setBalance(newBalance);
                moneyLog.setCreateTime(new Date());
                logMapper.insert(moneyLog);
                //
                IncomeLog in = new IncomeLog();
                in.setAmount(balance);
                in.setIncomeType("8");
                in.setUserId(clientUser.getId());
                incomeLogService.saveInComeLog(in);
                // 获取总计充值数额 设置VIP级别
                Float moneyAll = moneyLogService.sumMoney(clientUser);
                if (moneyAll >= 200 && moneyAll <= 400) {
                    clientUser.setVipLevel(1);
                } else if (moneyAll > 400 && moneyAll <= 1000) {
                    clientUser.setVipLevel(2);
                } else if (moneyAll > 1000 && moneyAll <= 2000) {
                    clientUser.setVipLevel(3);
                } else if (moneyAll > 2000 && moneyAll <= 10000) {
                    clientUser.setVipLevel(4);
                } else if (moneyAll > 10000 && moneyAll <= 20000) {
                    clientUser.setVipLevel(5);
                } else if (moneyAll > 20000 && moneyAll <= 50000) {
                    clientUser.setVipLevel(6);
                } else if (moneyAll > 50000 && moneyAll <= 100000) {
                    clientUser.setVipLevel(7);
                } else if (moneyAll > 100000) {
                    clientUser.setVipLevel(8);
                }
                clientUser.setBalance(newBalance);
                clientUser.setAwayBalance(clientUser.getAwayBalance() + rechargeOrder.getExtra());
                userService.updateClientUser(clientUser);
                if (clientUser.getAwayBalance() != null && clientUser.getAwayBalance() > 0) {
                    IncomeLog incomeLog = new IncomeLog();
                    incomeLog.setAmount(10f);
                    incomeLog.setIncomeType("8");
                    incomeLog.setUserId(clientUser.getId());
                    incomeLogService.saveInComeLog(incomeLog);
                }
                rechargeOrder.setOrderStatus("1");
                rechargeOrderService.updateRechargeOrder(rechargeOrder);
            }
            pw.print("success");
            System.out.println("验签结果result的值：" + result + " -->success");
        } else {
            rechargeOrder.setOrderStatus("2");
            rechargeOrderService.updateRechargeOrder(rechargeOrder);
            pw.print("Signature Error");
            System.out.println("验签结果result的值：" + result + " -->Signature Error");
        }
    }

    /**
     * @Description: [提现回调]
     * @Title: withdrawCallBack
     * @Author: SUNLEI
     * @Date: 2023-04-23
     * @Param: request
     * @Param: response
     * @Return: void
     * @Throws:
     */
    @RequestMapping("/withdrawCallBack")
    public void withdrawCallBack(HttpServletRequest request, HttpServletResponse response) {
        String merchant_key = "";
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        String tradeResult = (String) request.getParameter("tradeResult");
        String merTransferId = (String) request.getParameter("merTransferId");
        String merNo = (String) request.getParameter("merNo");
        String tradeNo = (String) request.getParameter("tradeNo");
        String transferAmount = (String) request.getParameter("transferAmount");
        String sign = (String) request.getParameter("sign");
        String signType = (String) request.getParameter("signType");
        String applyDate = (String) request.getParameter("applyDate");
        String version = (String) request.getParameter("version");
        String respCode = (String) request.getParameter("respCode");

        System.out.println("tradeResult = " + tradeResult + "\n" + "merTransferId = " + merTransferId + "\n"
                + "merNo = " + merNo + "\n" + "tradeNo = " + tradeNo + "\n" + "transferAmount = " + transferAmount
                + "\n" + "sign = " + sign + "\n" + "signType = " + signType + "\n" + "applyDate = " + applyDate
                + "\n" + "signType = " + signType + "\n" + "version = " + version + "\n" + "respCode = " + respCode
                + "\n");

        Map<String, String> signStr = new LinkedHashMap<String, String>();
        signStr.put("tradeResult", tradeResult);
        signStr.put("merTransferId", merTransferId);
        signStr.put("merNo", merNo);
        signStr.put("tradeNo", tradeNo);
        signStr.put("transferAmount", transferAmount);
        signStr.put("applyDate", applyDate);
        signStr.put("version", version);
        signStr.put("respCode", respCode);

        String signInfo = SignUtil.sortData(signStr);
        System.out.println(signInfo.length() + " -->" + signInfo);
        System.out.println(sign.length() + " -->" + sign);
        boolean result = false;

        if ("MD5".equals(signType)) {
            result = SignAPI.validateSignByKey(signInfo, merchant_key, sign);
        }

        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if (result) {
            pw.print("success");
            pw.flush();
            pw.close(); // 验签成功，响应SUCCESS
            System.out.println("验签结果result的值：" + result + " -->SUCCESS");
        } else {
            pw.print("Signature Error");
            pw.flush();
            pw.close(); // 验签失败，业务结束
            System.out.println("验签结果result的值：" + result + " -->Signature Error");
        }
    }
}
